package jyrc;



import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import org.jdom.*;





/**
 * This reprezents a post with his author and his date.
 * JyRCPost fills tasks like testing if this post is a command or not; making XML elements (which are sended to the client).
*/



public final class JyRCPost {
	protected static final DateFormat RFC822out = new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z", Locale.US);

	private final String txt, author;
	private JyRCServer user;
	private final Date date;
	private String cmd=null, args=null;

	public JyRCPost(String txt, String author, Date date) {
		this.txt = txt!=null? txt : "";
		this.author = author;
		this.date = date!=null? new Date(date.getTime()) : new Date();
	}
	public JyRCPost(String txt, JyRCServer user, Date date)	{ this(txt, user.username(),date);
		this.user = user;
	}
	public JyRCPost(String txt, String author)		{ this(txt, author,null); }
	public JyRCPost(String txt, JyRCServer user)		{ this(txt, user,null); }
	public JyRCPost(String txt)				{ this(txt, (String)null); }

	public String getText() { return txt; }
	public String getAuthor() { return author; }
	public JyRCServer getUser() { return user; }
	public Date getDate() { return new Date(date.getTime()); }



	public boolean isACommand() { return txt.length() > 0 && txt.charAt(0) == '/'; }
	public boolean isAnInternalCommand() { return isACommand() && txt.length() > 1 && txt.charAt(1) == '#'; }

	private void extractCommandInfos() { if(!isACommand()) return;
		int idx = txt.indexOf(" ");
		cmd = txt.substring(isAnInternalCommand()?2:1, idx>0? idx:txt.length());
		args= idx>0? txt.substring(idx+1, txt.length()) : "";
	}
	public String getCommandName() { if(!isACommand()) return null;
		if(cmd == null || args == null)
			extractCommandInfos();
		return cmd;
	}
	public String getCommandArgs() { if(!isACommand()) return null;
		if(cmd == null || args == null)
			extractCommandInfos();
		return args;
	}



	public Element toXmlElement() {
		Element xmlElement = new Element("post");
		xmlElement.setText(txt);
		if(author != null)
			xmlElement.setAttribute("author",author);
		xmlElement.setAttribute("date",RFC822out.format(date));
		return xmlElement;
	}
	@Override public String toString() { return "["+date+"] "+author+"> "+txt; }
}
